//
//  HNGiveAwayFlowerVCViewController.m
//  优学荟管理系统
//
//  Created by edz on 2017/11/14.
//  Copyright © 2017年 星道三好. All rights reserved.
//

#import "HNGiveAwayFlowerVCViewController.h"
#import "UIButton+HNActivity.h"
#import "HNGiveAwayFlowerModel.h"
#import "HNGiveAwayFlowerCell.h"
#import "HNGiveAwayFlowerView.h"

@interface HNGiveAwayFlowerVCViewController ()<UITableViewDelegate, UITableViewDataSource>
{
    __weak IBOutlet UITableView *_TableView;
    __weak IBOutlet UIButton *_AllSelectBtn;
    __weak IBOutlet UIButton *_GiveAwayBtn;
    HNGiveAwayFlowerView *_View;
}
/** 数据存放地 */
@property (nonatomic, strong) NSMutableArray *DataArr;
/** 当前的页 */
@property (nonatomic, assign) NSInteger CurrentPage;
/** 临时保存的页数 */
@property (nonatomic, assign) NSInteger TempPage;
/** 剩余可送的花数，一天只能送出100朵 */
@property (weak, nonatomic) IBOutlet UILabel *_FlowerNum;

@end

@implementation HNGiveAwayFlowerVCViewController


#pragma mark - 生命周期
- (void)viewDidLoad {
    
    [super viewDidLoad];
    
    self.title = @"赠送红花";
    
    // 配置TableView
    [self ConfigTableView];
}

#pragma mark - Config
/** 配置TableView */
- (void)ConfigTableView {
    // 设置代理
    _TableView.delegate = self;
    _TableView.dataSource = self;
    // 设置占位View
    _TableView.tableFooterView = [UIView new];
    _TableView.tableHeaderView = [UIView new];
    // 设置自动Cell高
    _TableView.rowHeight = 44*KScale;
    // 设置预注册
    [_TableView registerNib:[UINib nibWithNibName:[HNGiveAwayFlowerCell description] bundle:nil] forCellReuseIdentifier:@"Cell"];
    // 增加刷新头
    _TableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        // 每次下拉刷新时都保存好当前的页数，预防刷新失败后页数错乱
        self.TempPage = self.CurrentPage;
        // 当前的刷新设为1
        self.CurrentPage = 1;
        // 获取数据
        [self RefreshData];
    }];
    // 增加刷新尾
    _TableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        // 获取数据
        [self RefreshData];
    }];
    // 开始刷新
    [_TableView.mj_header beginRefreshing];
}

/** 刷新失败时的页数处理 */
- (void)MgrPage {
    
    self.CurrentPage = self.TempPage;
}

/** 刷新状态 1结束刷新 2没有更多数据了 3刷新表单*/
- (void)MgrRefresh:(NSInteger)State {
    
    if (State == 1) {
        [_TableView.mj_header endRefreshing];
        [_TableView.mj_footer endRefreshing];
    } else if (State == 2) {
        [_TableView.mj_footer endRefreshingWithNoMoreData];
    } else if (State == 3) {
        [_TableView reloadData];
    } else  {
        // 无
    }
}

#pragma mark - 网络
- (void)RefreshData {
    
    NSDictionary *Params = @{
                             @"action":@"getEnrollSel",
                             @"pageNumber":@(self.CurrentPage)
                             };
    [NetManager Get:LLBaseURL(@"yxhUser.do") Auth:YES Params:Params Success:^(id responseObj) {
        
        // 结束刷新
        [self MgrRefresh:1];
        // 数据处理
        if ([responseObj[@"code"] isEqualToNumber:@1000]) {
            // 拿到数据
            NSArray *Arr = responseObj[@"t"][@"dataList"];
            // 如果当前的页码是1就先清空原数据
            self.CurrentPage == 1 ? [self.DataArr removeAllObjects]:nil;

            // 如果没有数据就提示没数据了
            if (Arr.count == 0) {
                
                [self MgrRefresh:2];
            } else {
                // 终于有数据啦
                [Arr enumerateObjectsUsingBlock:^(NSDictionary * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                    // 处理模型转对象
                    HNGiveAwayFlowerModel *Model = [[HNGiveAwayFlowerModel alloc] init_ValuForKeyWithDict:obj];
                    Model.Selected = _AllSelectBtn.selected;
                    self._FlowerNum.text = [@(100 + [Model.flowers integerValue]) stringValue];
                    [self.DataArr addObject:Model];
                }];
                self.CurrentPage += 1;
                [self MgrRefresh:3];
            }
        } else {
            // 数据获取失败
            [SVProgressHUD showErrorWithStatus:responseObj[@"msg"]];
            [self MgrPage];
        }
    } Fail:^(NSError *error) {
        
        [SVProgressHUD showErrorWithStatus:NetErr];
        [self MgrRefresh:1];
        [self MgrPage];
    }];
}

- (void)RefreshDataForFlower:(NSString *)Num Uids:(NSString *)Uids Complete:(void(^)())Complete {
    
    [SVProgressHUD showInfoWithStatus:@"处理中"];
    NSDictionary *Params = @{
                             @"action":@"sendFlowersFromTea",
                             @"flowers":Num,
                             @"uids":Uids
                             };
    [NetManager Get:LLBaseURL(@"yxhUser.do") Auth:YES Params:Params Success:^(id Obj) {
        
        if ([Obj[@"code"] isEqualToNumber:@1000]) {
            
            Complete ? Complete() : nil;
        } else {
            
            [SVProgressHUD showErrorWithStatus:Obj[@"msg"]];
        }
        
    } Fail:^(NSError *Error) {
        [SVProgressHUD showErrorWithStatus:NetErr];
    }];
}

#pragma mark - tableView delegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return self.DataArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    HNGiveAwayFlowerModel *Model = self.DataArr[indexPath.row];
    HNGiveAwayFlowerCell *Cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath];
    Cell.Model = Model;
    // 选择学生
    Cell.SelectAction = ^(HNGiveAwayFlowerModel *Model) {
        [self SelectAction:Model IndexPath:indexPath];
    };
    return Cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    
}

#pragma mark - 自定义方法

#pragma mark - 点击事件
- (IBAction)AllSelectAction:(UIButton *)sender {
    
    sender.selected = !sender.selected;
    [self.DataArr enumerateObjectsUsingBlock:^(HNGiveAwayFlowerModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        obj.Selected = sender.selected;
    }];
    [_TableView reloadSections:[NSIndexSet indexSetWithIndex:0] withRowAnimation:(UITableViewRowAnimationAutomatic)];
}
/** 选择学生 */
- (void)SelectAction:(HNGiveAwayFlowerModel *)Model IndexPath:(NSIndexPath *)IndexPath {
    // 选中状态互反
    Model.Selected = !Model.Selected;
    // 刷新单个Cell
    [_TableView reloadRowsAtIndexPaths:@[IndexPath] withRowAnimation:(UITableViewRowAnimationAutomatic)];
}

/** 赠送事件 */
- (IBAction)GiveAwayActioin:(UIButton *)sender {
    
    __block NSMutableArray *Arr = [NSMutableArray array];
    [self.DataArr enumerateObjectsUsingBlock:^(HNGiveAwayFlowerModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        obj.Selected == YES ? [Arr addObject:obj.uid]:nil;
    }];
    if (Arr.count == 0) {
        [SVProgressHUD showErrorWithStatus:@"暂无选择学生赠送!"];
        return;
    }
    
    
    HNGiveAwayFlowerView *View = [[HNGiveAwayFlowerView alloc] initWithVC:self Complete:nil];
    _View = View;
    View.SureAction = ^(NSString *Num) {
      
        NSInteger Index = ([Num integerValue] * Arr.count);
        if (Index * Arr.count > [self._FlowerNum.text integerValue]) {
            
            [SVProgressHUD showErrorWithStatus:@"红花数超出可以赠送数量!"];
        } else {
        
            [self RefreshDataForFlower:Num Uids:[Arr componentsJoinedByString:@","] Complete:^{
                // 请求成功
                [SVProgressHUD showSuccessWithStatus:@"赠送成功!"];
                self._FlowerNum.text = [@([self._FlowerNum.text integerValue] - Index) stringValue];
                [_View CloseMine];
            
            }];
        }
    };
    [self.view addSubview:View];
}
#pragma mark - Get
- (NSMutableArray *)DataArr {
    if (!_DataArr) {
        _DataArr = [NSMutableArray array];
    }
    return _DataArr;
}

@end

